﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Dispatcher;

using Api.SelfHost.AssemblyResolvers.Config;

namespace Api.SelfHost.AssemblyResolvers
{
    public class PreLoadAssemblyResolver : DefaultAssembliesResolver
    {
        public override ICollection<System.Reflection.Assembly> GetAssemblies()
        {
            var section = PreLoadAssemblySection.GetSection();
            if (section != null)
            {
                var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                foreach (AssemblyElement assemblyElement in section.AssemblyNames)
                {
                    var assemblyName = AssemblyName.GetAssemblyName(assemblyElement.AssemblyName);
                    if (!assemblies.Any(a => AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyName)))
                    {
                        AppDomain.CurrentDomain.Load(assemblyName);
                    }
                }
            }
            return base.GetAssemblies();
        }
    }
}
